package admin

import (
	"github.com/gin-gonic/gin"
	"go-admin-auth/app/models"
	"go-admin-auth/app/service"
	"go-admin-auth/gin_helper"
	"go-admin-auth/httpapi/dto"
)

type operationHandler struct {
}

var (
	OperationHandler = new(operationHandler)
)

func (h operationHandler) Query(c *gin.Context) {
	form := new(dto.OperationQueryForm)
	if err := c.ShouldBind(&form); err != nil {
		gin_helper.JsonErr(c, err)
		return
	}

	form.OrderBy = append(form.OrderBy, "system_id asc")
	form.OrderBy = append(form.OrderBy, "parent_id asc")
	form.OrderBy = append(form.OrderBy, "menu_id asc")
	form.OrderBy = append(form.OrderBy, "order_no asc")

	ret, err := service.OperationSrv.Query(form)
	if err != nil {
		gin_helper.JsonErr(c, err)
		return
	}
	gin_helper.JsonOk(c, ret)
}

func (h operationHandler) Get(c *gin.Context) {
	id, _ := gin_helper.ParamInt(c, "id")

	info, err := service.OperationSrv.Get(id)
	if err != nil {
		gin_helper.JsonErr(c, err)
		return
	}
	gin_helper.JsonOk(c, info)
}

func (h operationHandler) GetMulti(c *gin.Context) {
	info, err := service.OperationSrv.GetMulti(nil)
	if err != nil {
		gin_helper.JsonErr(c, err)
		return
	}
	gin_helper.JsonOk(c, info)
}

func (h operationHandler) Add(c *gin.Context) {
	info := new(models.TOperation)
	if err := c.ShouldBind(info); err != nil {
		gin_helper.JsonErr(c, err)
		return
	}
	if err := service.OperationSrv.Insert(info); err != nil {
		gin_helper.JsonErr(c, err)
		return
	}

	gin_helper.JsonOk(c, info)
}

func (h operationHandler) Edit(c *gin.Context) {
	info := new(models.TOperation)
	id, _ := gin_helper.ParamInt(c, "id")
	info.Id = id
	if err := c.ShouldBind(info); err != nil {
		gin_helper.JsonErr(c, err)
		return
	}

	if err := service.OperationSrv.Update(info); err != nil {
		gin_helper.JsonErr(c, err)
		return
	}

	gin_helper.JsonOk(c, info)
}

func (h operationHandler) Delete(c *gin.Context) {
	id, _ := gin_helper.ParamInt(c, "id")
	if err := service.OperationSrv.RealDelete(id); err != nil {
		gin_helper.JsonErr(c, err)
		return
	}

	gin_helper.JsonOk(c, "")
}
